package com.tangkun.environment.adapter;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.media.ThumbnailUtils;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;

import com.bumptech.glide.Glide;
import com.tangkun.environment.R;
import com.tangkun.environment.activity.DeleteImageActivity;
import com.tangkun.environment.activity.ImageActivity;
import com.tangkun.environment.network.GlobalUrl;
import com.tangkun.environment.utils.LogUtils;

import org.simple.eventbus.EventBus;

import java.io.File;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

/**
 * @author tangkun
 * @ClassName: ImageUrlNoAddAdapter
 * @Description: TODO(GirdView图片列表适配器(不含添加图片)) 图片地址
 * @date 2016年8月1日 下午1:37:03
 */
public class ImageUrlNoAddAdapter extends BaseAdapter {
    private int REQUEST_CODE = 1;// REQUEST_CODE
    private Activity activity;
    private LayoutInflater layoutInflater;
    private int res;
    /**
     * 可以删除或仅仅是展示
     */
    private boolean canDelete = false;

    /**
     * 编辑资料页面动态图片(GridView)对应的ID
     */
    private String idDongtaiImg = "";

    /**
     * 编辑资料页面动态图片(GridView)对应的ID
     *
     * @return
     */
    public String getIdDongtaiImg() {
        return idDongtaiImg;
    }

    /**
     * 编辑资料页面动态图片(GridView)对应的ID
     *
     * @param idDongtaiImg
     */
    public void setIdDongtaiImg(String idDongtaiImg) {
        this.idDongtaiImg = idDongtaiImg;
    }

    public ImageUrlNoAddAdapter(Activity activity, int res) {
        this.activity = activity;
        this.layoutInflater = LayoutInflater.from(activity);
        this.res = res;
    }

    public int getREQUEST_CODE() {
        return REQUEST_CODE;
    }

    public void setREQUEST_CODE(int REQUEST_CODE) {
        this.REQUEST_CODE = REQUEST_CODE;
    }

    private List<String> urlList = new ArrayList<String>();

    public List<String> getUrlList() {
        if (urlList == null) {
            urlList = new ArrayList<String>();
        }
        return urlList;
    }

    public void setUrlList(List<String> fileList) {
        this.urlList.clear();
        this.urlList.addAll(fileList);
    }

    public boolean isCanDelete() {
        return canDelete;
    }

    public void setCanDelete(boolean canDelete) {
        this.canDelete = canDelete;
    }

    @Override
    public int getCount() {
        return urlList.size();
    }

    @Override
    public Object getItem(int arg0) {
        // return null;
        return urlList.get(arg0);
    }

    @Override
    public long getItemId(int arg0) {
        return arg0;
    }

    class ViewHolder {
        public ImageView imageView;
        public ImageView cameraImageView;
    }

    @Override
    public View getView(final int position, View convertView, ViewGroup viewGroup) {
        ViewHolder holder;
        if (convertView == null) {
            convertView = layoutInflater.inflate(res, null);
            holder = new ViewHolder();
            holder.imageView = (ImageView) convertView.findViewById(R.id.image);
            holder.cameraImageView = (ImageView) convertView.findViewById(R.id.camera_image);
            convertView.setTag(holder);
        } else {
            holder = (ViewHolder) convertView.getTag();
        }
        holder.cameraImageView.setVisibility(View.GONE);
        holder.imageView.setVisibility(View.VISIBLE);
        if (getItem(position).toString().endsWith(".png") || getItem(position).toString().endsWith(".jpg")) {
            //表示网络半路径
            Glide.with(activity)
                    .load(GlobalUrl.IMG_URL + getItem(position).toString())
                    .placeholder(R.mipmap.ic_place_holder)
                    .dontAnimate()
                    .into(holder.imageView);
        } else {
            //表示本地文件地址
            // 由于现在可以传原图回来，所以这里要显示缩略图，否则会内存溢出的，因此不能采用ImageLoader那种图片展示方式了
            holder.imageView.setImageBitmap(getImageThumbnail(getItem(position).toString(), 200, 200));
        }

        // ImageLoader.getInstance().displayImage(Uri.fromFile(fileList.get(position)).toString(),
        // holder.imageView);

        // 点击查看大图
        holder.imageView.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                if (!TextUtils.isEmpty(idDongtaiImg)) {
                    //发送通知给编辑资料/提交数据页面，更新动态图片ID
                    Intent idsIntent = new Intent();
                    idsIntent.putExtra("ids", idDongtaiImg);
                    EventBus.getDefault().post(idsIntent, "BianJiZiLiaoActivity.refreshgDongtaiIds");

                }

                if (canDelete) {// 可以删除
                    // 预览图片，可以删除
                    List<File> fileList = new ArrayList<File>();
                    if (urlList != null) {
                        for (int i = 0; i < urlList.size(); i++) {
                            fileList.add(new File(urlList.get(i)));
                        }
                    }
                    Intent intent = new Intent(activity, DeleteImageActivity.class);
                    intent.putExtra("urlList", (Serializable) urlList);
                    intent.putExtra("fileList", (Serializable) fileList);// 传递文件的集合过去
                    intent.putExtra("index", position);
                    activity.startActivityForResult(intent, REQUEST_CODE);
                } else {
                    // 预览图片,不可以删除
                    List<String> urlList = new ArrayList<String>();
                    Intent intent = new Intent(activity, ImageActivity.class);
                    intent.putExtra("urlList", (Serializable) urlList);
                    intent.putExtra("index", position);
                    activity.startActivity(intent);
                }
            }
        });
        return convertView;
    }

    /**
     * 根据指定的图像路径和大小来获取缩略图 此方法有两点好处： 1.
     * 使用较小的内存空间，第一次获取的bitmap实际上为null，只是为了读取宽度和高度，
     * 第二次读取的bitmap是根据比例压缩过的图像，第三次读取的bitmap是所要的缩略图。 2.
     * 缩略图对于原图像来讲没有拉伸，这里使用了2.2版本的新工具ThumbnailUtils，使 用这个工具生成的图像不会被拉伸。
     *
     * @param imagePath 图像的路径
     * @param width     指定输出图像的宽度
     * @param height    指定输出图像的高度
     * @return 生成的缩略图
     */
    private Bitmap getImageThumbnail(String imagePath, int width, int height) {
        Bitmap bitmap = null;
        BitmapFactory.Options options = new BitmapFactory.Options();
        options.inJustDecodeBounds = true;
        // 获取这个图片的宽和高，注意此处的bitmap为null
        bitmap = BitmapFactory.decodeFile(imagePath, options);
        options.inJustDecodeBounds = false; // 设为 false
        // 计算缩放比
        int h = options.outHeight;
        int w = options.outWidth;
        int beWidth = w / width;
        int beHeight = h / height;
        int be = 1;
        if (beWidth < beHeight) {
            be = beWidth;
        } else {
            be = beHeight;
        }
        if (be <= 0) {
            be = 1;
        }
        options.inSampleSize = be;
        // 重新读入图片，读取缩放后的bitmap，注意这次要把options.inJustDecodeBounds 设为 false
        bitmap = BitmapFactory.decodeFile(imagePath, options);
        // 利用ThumbnailUtils来创建缩略图，这里要指定要缩放哪个Bitmap对象
        bitmap = ThumbnailUtils.extractThumbnail(bitmap, width, height, ThumbnailUtils.OPTIONS_RECYCLE_INPUT);
        return bitmap;
    }

}
